package com.bulletelc.apollopre.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.os.AsyncTask;
import android.text.Html;
import android.view.View;
import android.widget.TextView;

import com.bulletelc.apollopre.R;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 作者：jerry
 * 日期：2018/6/22
 * 说明：解析Html中src的url
 */

public class URLImageParser implements Html.ImageGetter {

    private class URLDrawable extends BitmapDrawable {
        // the drawable that you need to set, you could set the initial drawing
        // with the loading image if you need to
        protected Drawable drawable;

        public URLDrawable() {

        }

        @Override
        public void draw(Canvas canvas) {
            // override the draw to facilitate refresh function later
            if (drawable != null) {
                drawable.draw(canvas);
            }
        }
    }

    private Context context;
    private View view;

    /***
     * 构建URLImageParser将运行AsyncTask,刷新容器
     * @param v
     * @param c
     */
    public URLImageParser(View v, Context c) {
        this.context = c;
        this.view = v;
    }

    @Override
    public Drawable getDrawable(String source) {
        LevelListDrawable d = new LevelListDrawable();
        Drawable empty = context.getResources().getDrawable(R.drawable.divider);
        d.addLevel(0, 0, empty);
        d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());

        new LoadImage().execute(source, d);

        return d;

//        URLDrawable urlDrawable = new URLDrawable();
//
//        //TODO ImageLoader
//        // 获得实际的源
//        ImageGetterAsyncTask asyncTask = new ImageGetterAsyncTask( urlDrawable);
//
//        asyncTask.execute(source);
//
//        //返回引用URLDrawable将改变从src与实际图像标记
//        return urlDrawable;

    }

    class LoadImage extends AsyncTask<Object, Void, Bitmap> {

        private LevelListDrawable mDrawable;

        @Override
        protected Bitmap doInBackground(Object... params) {
            String source = (String) params[0];
            mDrawable = (LevelListDrawable) params[1];
            try {
                InputStream is = new URL(source).openStream();
                return BitmapFactory.decodeStream(is);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                BitmapDrawable d = new BitmapDrawable(bitmap);
                mDrawable.addLevel(1, 1, d);
                mDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
                mDrawable.setLevel(1);
                // i don't know yet a better way to refresh TextView
                // mTv.invalidate() doesn't work as expected
                CharSequence t = ((TextView) view).getText();
                ((TextView) view).setText(t);
            }
        }
    }

    public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
        URLDrawable urlDrawable;

        public ImageGetterAsyncTask(URLDrawable drawable) {
            this.urlDrawable = drawable;
        }

        @Override
        protected Drawable doInBackground(String... params) {
            String source = params[0];
            return fetchDrawable(source);
        }

        @Override
        protected void onPostExecute(Drawable result) {
            // set the correct bound according to the result from HTTP call
            urlDrawable.setBounds(0, 0, 0 + result.getIntrinsicWidth(), 0
                    + result.getIntrinsicHeight());

            // change the reference of the current drawable to the result
            // from the HTTP call
            urlDrawable.drawable = result;

            // redraw the image by invalidating the container
            URLImageParser.this.view.invalidate();
        }

        /***
         * 得到Drawable的URL
         *
         * @param urlString
         * @return
         */
        private Drawable fetchDrawable(String urlString) {
            try {
                URL url = new URL(urlString);
                //使用Drawable.createFromResourceStream可以使图片按原图大小展示出来不会出现加载后图片变小的情况  ，使用Drawable.createFromStream会。
                Drawable drawable = Drawable.createFromResourceStream(context.getResources(), null, url.openStream(), "src", null);
                if (drawable != null) {
                    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                    return drawable;
                } else {
                    return null;
                }
            } catch (Exception e) {
                return null;
            }
        }
    }

}
